package net.takela.push.service.sp.impl;


import net.takela.common.spring.exception.ParamException;
import net.takela.common.spring.http.HttpRequestBuilder;
import net.takela.common.spring.http.HttpResponse;
import net.takela.common.spring.http.StatusCode;
import net.takela.common.utils.JSONUtils;
import net.takela.common.utils.StringUtils;
import net.takela.push.model.PushApp;
import net.takela.push.model.PushMsgTpl;
import net.takela.push.service.sp.ServiceProvider;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * Created by baboy on 25/07/2017.
 */
@Service("sendCloudPushService")
public class SendCloudServiceProvider extends ServiceProvider {
    private static final Logger logger = LoggerFactory.getLogger(SendCloudServiceProvider.class);


    public boolean sendTplMsg(String mobile, String tempId, Map params) {
        Map<String, Object> appConf = getPushApp().getConf();
        String host = (String)appConf.get("host");
        String smsUser = (String)appConf.get("smsUser");
        String smsKey = (String)appConf.get("smsKey");
        String vars = JSONUtils.toString(params);
        // 对参数进行排序
        Map<String, String> d = new TreeMap<String, String>(new Comparator<String>() {
            @Override
            public int compare(String arg0, String arg1) {
                // 忽略大小写
                return arg0.compareToIgnoreCase(arg1);
            }
        });

        d.put("smsUser", smsUser);
        d.put("phone", mobile);
        //发送语音验证码
        if (tempId.equals("voice-sms-code")){
            host = (String)appConf.get("send_voice_api");
            Object code = params.get("smsCode");
            if (code == null){
                Object[] a = params.values().toArray();
                if (a != null && a.length>0){
                    code = a[0];
                }
            }
            if (code == null){
                return false;
            }
            d.put("code", code.toString());
        }else{
            d.put("templateId", tempId);
            d.put("msgType", "0");
            d.put("vars", vars);
        }

        // 计算签名
        StringBuilder sb = new StringBuilder();
        sb.append(smsKey).append("&");
        for (String k : d.keySet()) {
            sb.append(String.format("%s=%s&", k, d.get(k)));
        }
        sb.append(smsKey);
        String signature = DigestUtils.md5Hex(sb.toString());

        d.put("signature", signature);


        try {
            HttpResponse<?> responese = HttpResponse.success();
            Map<String, Object> oriData = (Map<String, Object>) HttpRequestBuilder.builder().setHttpMethod(HttpMethod.POST).setBaseUrl(host).setRequestBody(d).build().request();
            if (oriData != null){
                boolean flag = oriData.containsKey("result") ? (Boolean) oriData.get("result") : true;
                if (!flag){
                    responese = new HttpResponse();
                    responese.setCode(StatusCode.ERROR.getCode());
                    responese.setMessage(oriData.get("message").toString());
                }
            }
            logger.info("SEND SMS|sp:sendcloud|"+responese.toString());
            return responese.isSuccess();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    @Override
    public HttpResponse send(String msgCode, Map data, String ip) {
        PushMsgTpl msgTpl = getMsgTpl(msgCode);
        Map conf = msgTpl.getConf();
        Map dataMap = new HashMap();
        if(conf.containsKey("data")){
            dataMap.putAll( (Map)conf.get("data") );
        }
        dataMap.putAll(data);
        String mobiles = (String)dataMap.get("mobile");

        if (org.apache.commons.lang3.StringUtils.isEmpty(mobiles)){
            throw new ParamException("param.error.desc","mobile");
        }

        HttpResponse ret;
        Map<String, String> params = new HashMap<String, String>();
        if (conf.containsKey("keys")){
            Map<String,String> keys = (Map) conf.get("keys");
            for (Map.Entry<String, String> keyMap :keys.entrySet()){
                String k = keyMap.getKey();
                String k2 = keyMap.getValue();
                Object ov = dataMap.get(k2);
                String v = ov==null ? null:ov.toString();
                if(v != null){
                    v = StringUtils.formatPlaceholders(v,dataMap);
                }
                params.put(k, v);
            }
        }

        ret = HttpResponse.success();
        try {
            String[] a = mobiles.split(",");
            for (String mobile :  a){
                boolean f = sendTplMsg( mobile, msgTpl.getMsgId(), params);
                if (!f){
                    ret =  HttpResponse.error();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            ret.setMessage(e.getMessage());
        }
        return ret;
    }
}
